<?php
/**
 * @copyright meila.com
 * @author shaopu@
 * @name 
 * @param 
 *         $xxx = 作用
 * @static 
 *         XXX = 作用
 * 
 * 
 */
$dir = dirname(dirname(__FILE__));
include($dir.'/__queue_global.php');
include(SERVER_ROOT_PATH.'/include/config/ml_search_config.php');


class ml_mq_search_content extends MqClass{
    const QUEUE_NAME = ML_QUEUENAME_SEARCH_CONTENT;
    const SEARCH_RSYNC_FILE_DIR = ML_SEARCH_TMP_CONTENT_DIR;
    const SEARCH_RSYNC_FILE_LOG = ML_SEARCH_TMP_CONTENT_FAIL;
    const SEARCH_RSYNC_FILE_EMPTY = ML_SEARCH_TMP_CONTENT_EMPTY;
    private $oContent;
    private $oRdsCnt;
    
    
public function __construct($queue)
    {
        $this->oContent = new ml_model_dbContent();
        $this->oRdsCnt = new ml_model_rdsCount();
        
        parent::__construct($queue);
    }    
    
    public function run_job(){
        //接收的数据
        $arr = $this->src_data;
        
        $DF = $arr['dealtype']; 
        $rid = $arr['rid'];
        $updateArr = $arr['updateArr'];
        
        $mlCdata['DF'] = $DF;
        $mlCdata['rid'] = $rid;
        
        if (!ml_tool_resid::is_resid($rid)) {
            return ;
        }
        
        
        switch ($DF) {
            case 'D':
                break;//待沟通如何处理删除
            case 'U'://暂时和新建一样
            case 'A':
                $rs = $this->oContent->get_by_rid($rid);
                if (!$rs) {
                    Tool_logger::dataLog('search_content_fail' , $rid);
                    //ml_tool_sendMq::search_content($DF, $rid);
                    return ;
                }
                $data = $this->oContent->get_data();
                if (empty($data)) {
                    $str = $mlCdata['rid']. "\r\n";
                    $this->emptyWriteToFile($str);
                    return ;
                }
                
                $url = $data['gd_info']['gd_url'];
                
                $pv = 0;//待续
                $this->oRdsCnt->getAttitudeCount(array($rid));
                $like_score = $this->oRdsCnt->get_data();
                $atti_sum = intval($like_score[$rid]);
                
                $hot_rank = ml_tool_hotrank::calc_search_hotrank($atti_sum, $pv);
    
                $mlCdata['gd_title'] = $data['gd_title'];            
                $mlCdata['content'] = $data['content'];
                $mlCdata['uid'] = $data['uid'];
                $mlCdata['type'] = $data['type_xrank'];
                $mlCdata['pic_id'] = $data['pic_id'];  
                $mlCdata['tags'] = '';//暂时无用
                $mlCdata['from'] = $data['from'];
                $mlCdata['status'] = $data['status'];
                $mlCdata['ctime'] = $data['ctime']; 
                $mlCdata['price'] = $data['gd_price'];
                $mlCdata['hotrank'] = $hot_rank;
                $mlCdata['atti_sum'] = $atti_sum; 
                $mlCdata['shopfrom'] = $this->pickUpShop($url);
                $mlCdata['gd_info'] = serialize($data['gd_info']);
                $mlCdata['userfeed_rid'] = $data['userfeed_rid'];
                break;
            default:
                return ;
        }
        
      
            $push_msg = $this->parseLogFomat($mlCdata);
            if ($push_msg !== false) {
                $this->writeToFile($push_msg);
            }
        
      
        return true;
    }
    
    /**
     * 
     */
    public function pickUpShop( $url) {
        
        $host=array('com','cn','net','hk','org','cc','mobi','info','so','co');
        $url_arr = parse_url($url);
        $host_arr = explode('.',$url_arr['host']);
        while ($a = array_pop($host_arr)){
            if(!in_array($a,$host)){
                $shop=$a;
                break;
            }
        }
        
        switch($shop){
            case 'ing2ing':
            case 'rutisher':
            case 'suorang':
            case 'baoyeah':
            case 'clafield':
            case 'qjherb':
                $shop='moonbasa';
                break;
            case 'shishang71':
                $shop='shishangqiyi';
                break;
            case 'qq':
                $shop='paipai';
                break;
        }

        $banana = array( 'taobao' => 1,
                         'tmall' => 2,
                         'vancl' => 3,
                         'm18' => 4,
                         'paipai' => 5,
                         'moonbasa' => 6,
                         'mbaobao' => 7,
                         'shishangqiyi' => 8,
                         '5lux' => 9,
                         'lamiu' => 10,
                         'letao' => 11,
                         'okbuy' => 12,
        );
        
        return intval($banana[$shop]);
    }
    
    /**
     * 写入日志文件
     *  
     */
    public function writeToFile( $str ){
             
        $filename = self::SEARCH_RSYNC_FILE_DIR.'meila_gd_'.date("Y-m-d_H:i").'.txt';
        
        if (!is_dir(self::SEARCH_RSYNC_FILE_DIR)) mkdir(self::SEARCH_RSYNC_FILE_DIR, 0700, true);
        
        $fp = fopen($filename, "ab");        
        // 进行排它型锁定
        if (flock($fp, LOCK_EX)) { 
            fwrite($fp, $str);
            flock($fp, LOCK_UN); 
            fclose($fp);
            return true; 
        } else {
            fclose($fp);
            return false;
        }  
    }
    
    public function emptyWriteToFile( $str ){
             
        $filename = self::SEARCH_RSYNC_FILE_EMPTY.'meila_empty_'.date("Y-m-d").'.txt';
        
        if (!is_dir(self::SEARCH_RSYNC_FILE_EMPTY)) mkdir(self::SEARCH_RSYNC_FILE_EMPTY, 0700, true);
        
        $fp = fopen($filename, "ab");        
        // 进行排它型锁定
        if (flock($fp, LOCK_EX)) { 
            fwrite($fp, $str);
            flock($fp, LOCK_UN); 
            fclose($fp);
            return true; 
        } else {
            fclose($fp);
            return false;
        }  
    }
    
    
    public function logWriteToFile( $str ){
             
        $filename = self::SEARCH_RSYNC_FILE_LOG.'meila_log_'.date("Y-m-d").'.txt';
        
        if (!is_dir(self::SEARCH_RSYNC_FILE_LOG)) mkdir(self::SEARCH_RSYNC_FILE_LOG, 0700, true);
        
        $fp = fopen($filename, "ab");        
        // 进行排它型锁定
        if (flock($fp, LOCK_EX)) { 
            fwrite($fp, $str);
            flock($fp, LOCK_UN); 
            fclose($fp);
            return true; 
        } else {
            fclose($fp);
            return false;
        }  
    }
    
  /**
     * 解析数据成要推送的格式
     * @param array $data
     */
    public function parseLogFomat( $data ){
        if( !$data['rid'] ){
            return false;
        }
           
        $push_msg  = "@\r\n";
           foreach( $data as $key=>$val ){
               $key = trim( $key );
               $val = trim( $val ); 
               //如果反序列化后是个数组，不直接转发，而是对数组里的value转发后，再序列化回去             
               
               $array = unserialize( $val );
               
               if(is_array( $array ) ){                          
                   $arrayNew = $this->encodeArray( $array );
                   $val = serialize($arrayNew);
               }else{
                   $val = mb_convert_encoding( $val, 'GBK' , 'utf-8' );
               }
               $push_msg .= "@".$key.":".$val." \r\n";
           }
           
           $push_msg .= "\r\n";
           return $push_msg;       
    }
    
    /**
     * 
     * 递归把数组里的内容都转换成gbk编码
     * @param $array
     */
    public function encodeArray( $array ){
        $arrayTmp = array();
        foreach ($array as $k=>$v ){
            if(is_array($v)){
                $arrayTmp[$k] = $this->encodeArray( $v );
            }else{
                $arrayTmp[$k] = mb_convert_encoding( $array[$k], 'GBK' , 'utf-8' );
            }
        }
        return $arrayTmp;
    }

}

ml_run_queue_check(ml_mq_search_content::QUEUE_NAME);
$xblog_obj = new ml_mq_search_content(new McQueue(ml_mq_search_content::QUEUE_NAME));
$argv[1]   = __FILE__;
$xblog_obj->setArgv($argv[1]);
$xblog_obj->execute();